package com.xtravel.common.handler;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import com.xtravel.common.exception.BusinessException;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.io.*;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Properties;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;

/**
 * @author kuner
 *
 * 统一异常处理.
 *
 * 15-8-31.
 */
public class GlobalExceptionHandler implements Thread.UncaughtExceptionHandler {

    /**
     * Debug Log Tag.
     */
    public static final String TAG = "GlobalExceptionHandler";

    /**
     * 是否开启日志输出, 在Debug状态下开启, 在Release状态下关闭以提升程序性能.
     */
    public static final boolean DEBUG = true;

    /**
     * GlobalExceptionHandler实例.
     */
    private static GlobalExceptionHandler INSTANCE;

    /**
     * 程序的Context对象.
     */
    private Context context;

    private static final String EX_KEY = "ex";

    /**
     * 系统默认的UncaughtException处理类.
     */
    private Thread.UncaughtExceptionHandler defaultHandler;

    /**
     * 异常处理器.
     */
    private Handler handler;

    /**
     * 使用Properties来保存设备的信息和错误堆栈信息
     */
    private Properties mDeviceCrashInfo = new Properties();
    private static final String VERSION_NAME = "versionName";
    private static final String VERSION_CODE = "versionCode";
    private static final String STACK_TRACE = "STACK_TRACE";
    /**
     * 错误报告文件的扩展名
     */
    private static final String CRASH_REPORTER_EXTENSION = ".cr";

    /**
     * 保证只有一个GlobalExceptionHandler实例
     */
    private GlobalExceptionHandler() {
        handler = new Handler() {
            private boolean isHandled;

            @Override public void handleMessage(Message msg) {
                if (!isHandled) {
                    handleException(msg);
                    isHandled = true;
                }
            }

            @Override public void dispatchMessage(Message msg) {
                int a = 1;
                super.dispatchMessage(msg);
            }

            @Override public String getMessageName(Message message) {
                int a = 1;
                return super.getMessageName(message);
            }

            @Override public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
                if (!isHandled) {
                    handleException(msg);
                    isHandled = true;
                }
                return true;
                //return super.sendMessageAtTime(msg, uptimeMillis);
            }

            @Override public String toString() {
                int a = 1;
                return super.toString();
            }

            private void handleException(Message msg) {
                Bundle bundle = msg.getData();
                if (bundle != null && bundle.getSerializable(EX_KEY) != null) {
                    Throwable throwable = (Throwable) bundle.getSerializable(EX_KEY);
                    if (throwable instanceof BusinessException) {
                        // 业务异常
                        Toast.makeText(context, "aaaaa", Toast.LENGTH_SHORT).show();
                    }else if (throwable instanceof IOException) {
                        // 网络异常
                        Toast.makeText(context, ">o_o< 网络不能用了", Toast.LENGTH_SHORT).show();
                    } else {
                        Log.e(TAG, "Error：", throwable);
                        // 其他异常
                        Toast.makeText(context, "啊哦，攻城狮罢工了", Toast.LENGTH_SHORT).show();
                        // 收集设备信息
                        collectCrashDeviceInfo(context);
                        // 保存错误报告文件
                        saveCrashInfoToFile(throwable);
                        // 发送错误报告到服务器
                        sendCrashReportsToServer(context);
                        try {
                            TimeUnit.SECONDS.sleep(2);
                        } catch (InterruptedException e) {
                            Log.e(TAG, "Error : ", e);
                        }
                        android.os.Process.killProcess(android.os.Process.myPid());
                        System.exit(0);
                    }
                }
            }
        };
    }

    /**
     * 获取GlobalExceptionHandler实例 ,单例模式
     */
    public synchronized static GlobalExceptionHandler getInstance() {
        if (INSTANCE == null)
            INSTANCE = new GlobalExceptionHandler();
        return INSTANCE;
    }

    /**
     * 初始化,注册Context对象, 获取系统默认的UncaughtException处理器, 设置该CrashHandler为程序的默认处理器
     *
     * @param ctx
     */
    public void init(Context ctx) {
        context = ctx;
        defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override public void uncaughtException(Thread thread, final Throwable ex) {
        if (ex != null) {
            Throwable throwable = ExceptionUtils.getRootCause(ex);
            Message msg = handler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putSerializable(EX_KEY, throwable);
            msg.setData(bundle);
            handler.sendMessage(msg);
        } else {
            int a = 1;
        }
    }

    /**
     * 收集程序崩溃的设备信息
     *
     * @param ctx Context.
     */
    public void collectCrashDeviceInfo(Context ctx) {
        try {
            // Class for retrieving various kinds of information related to the
            // application packages that are currently installed on the device.
            // You can find this class through getPackageManager().
            PackageManager pm = ctx.getPackageManager();
            // getPackageInfo(String packageName, int flags)
            // Retrieve overall information about an application package that is installed on the system.
            // public static final int GET_ACTIVITIES
            // Since: API Level 1 PackageInfo flag: return information about activities in the package in activities.
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                // public String versionName The version name of this package,
                // as specified by the <manifest> tag's versionName attribute.
                mDeviceCrashInfo.put(VERSION_NAME, pi.versionName == null ? "not set" : pi.versionName);
                // public int versionCode The version number of this package,
                // as specified by the <manifest> tag's versionCode attribute.
                mDeviceCrashInfo.put(VERSION_CODE, pi.versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "Error while collect package info", e);
        }
        // 使用反射来收集设备信息.在Build类中包含各种设备信息,
        // 例如: 系统版本号,设备生产商 等帮助调试程序的有用信息
        // 返回 Field 对象的一个数组，这些对象反映此 Class 对象所表示的类或接口所声明的所有字段
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                mDeviceCrashInfo.put(field.getName(), field.get(null));
                if (DEBUG) {
                    Log.d(TAG, field.getName() + " : " + field.get(null));
                }
            } catch (Exception e) {
                Log.e(TAG, "Error while collect crash info", e);
            }
        }
    }

    /**
     * 保存错误信息到文件中
     *
     * @param ex Context.
     *
     * @return 文件名
     */
    private String saveCrashInfoToFile(Throwable ex) {
        Writer info = new StringWriter();
        PrintWriter printWriter = new PrintWriter(info);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        String result = info.toString();
        printWriter.close();
        mDeviceCrashInfo.put(STACK_TRACE, result);
        try {
            long timestamp = System.currentTimeMillis();
            String fileName = "crash-" + timestamp + CRASH_REPORTER_EXTENSION;
            // 保存文件
            FileOutputStream trace = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            mDeviceCrashInfo.store(trace, "");
            trace.flush();
            trace.close();
            return fileName;
        } catch (Exception e) {
            Log.e(TAG, "an error occurred while writing report file...", e);
        }
        return null;
    }

    /**
     * 把错误报告发送给服务器,包含新产生的和以前没发送的.
     *
     * @param ctx Context.
     */
    private void sendCrashReportsToServer(Context ctx) {
        String[] crFiles = getCrashReportFiles(ctx);
        if (crFiles != null && crFiles.length > 0) {
            TreeSet<String> sortedFiles = new TreeSet<>();
            sortedFiles.addAll(Arrays.asList(crFiles));
            for (String fileName : sortedFiles) {
                File cr = new File(ctx.getFilesDir(), fileName);
                postReport(cr);
                // 删除已发送的报告
                cr.delete();
            }
        }
    }

    /**
     * 获取错误报告文件名.
     *
     * @param ctx Context.
     *
     * @return 文件名数组.
     */
    private String[] getCrashReportFiles(Context ctx) {
        File filesDir = ctx.getFilesDir();
        // 实现FilenameFilter接口的类实例可用于过滤器文件名
        FilenameFilter filter = new FilenameFilter() {
            // accept(File dir, String name)
            // 测试指定文件是否应该包含在某一文件列表中。
            public boolean accept(File dir, String name) {
                return name.endsWith(CRASH_REPORTER_EXTENSION);
            }
        };
        // 返回一个字符串数组，这些字符串指定此抽象路径名表示的目录中满足指定过滤器的文件和目录
        return filesDir.list(filter);
    }

    private void postReport(File file) {
        // TODO 使用HTTP Post 发送错误报告到服务器
    }

    /**
     * 在程序启动时候, 可以调用该方法来发送以前没有发送的报告.
     */
    public void sendPreviousReportsToServer() {
        sendCrashReportsToServer(context);
    }

}
